package com.jeesite.modules.dataScreen.ssm;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import lombok.Data;

@Data
public class SmsTmplateRule {

    //参数名
    private String paramName;
    //中文名，出错时使用
    private String chineseName;
    //是否可以为空
    private boolean allowNull;
    //最大长度
    private Integer maxLength;

    private SmsTmplateRule(String paramName, String chineseName, boolean allowNull, Integer maxLength) {
        this.paramName = paramName;
        this.chineseName = chineseName;
        this.allowNull = allowNull;
        this.maxLength = maxLength;
    }

    public static SmsTmplateRule build(String paramName, String chineseName, boolean allowNull, Integer maxLength) {
        return new SmsTmplateRule(paramName, chineseName, allowNull, maxLength);
    }

    public static SmsTmplateRule build(String paramName, String chineseName, boolean allowNull) {
        return new SmsTmplateRule(paramName, chineseName, allowNull, null);
    }

    public static SmsTmplateRule build(String paramName, String chineseName, Integer maxLength) {
        return new SmsTmplateRule(paramName, chineseName, false, maxLength);
    }

    public static void checkParam(JSONObject params, SmsTmplateRule... rules) {
        if (params == null) {
            throw new SmsTmpParamException("参数为null");
        }
        for (SmsTmplateRule rule : rules) {
            String paramsString = params.getString(rule.getParamName());
            if (paramsString == null) {
                paramsString = "";
            }
            int length = paramsString.length();

            if (rule.getMaxLength() != null && length > 0 && length > rule.getMaxLength()) {
                throw new SmsTmpParamException(rule.getChineseName() + "长度不能超过" + rule.getMaxLength());
            }
            if (!rule.isAllowNull() && StrUtil.isBlank(paramsString)) {
                throw new SmsTmpParamException(rule.getChineseName() + "不能为空");
            }
        }
    }
}
